import React, { useState, useEffect } from 'react'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Checkbox } from '@/components/ui/checkbox'
import { 
  FolderOpen, 
  FolderTree, 
  Building2,
  FileText,
  Download,
  ChevronRight,
  ChevronDown
} from 'lucide-react'
import { ExportType } from '@/lib/export-types'
import { cn } from '@/lib/utils'
import api, { ApiResponse } from '@/services/api'

interface DirectoryNode {
  id: string
  name: string
  type: 'folder' | 'file'
  children?: DirectoryNode[]
  hasChild?: boolean
}

interface DirectorySelectModalProps {
  isOpen: boolean
  onClose: () => void
  directories: DirectoryNode[]
  onExport: (type: ExportType, docId?: string, directoryId?: string, directoryName?: string) => void
  projectName: string
  currentSelectedDocId?: string // 当前选中的文档ID
  teamId?: string
  projectId?: string
}

export default function DirectorySelectModal({
  isOpen,
  onClose,
  directories,
  onExport,
  projectName,
  currentSelectedDocId,
  teamId,
  projectId
}: DirectorySelectModalProps) {
  const [selectedType, setSelectedType] = useState<ExportType>(ExportType.PROJECT)
  const [selectedDirectory, setSelectedDirectory] = useState<string>('')
  const [selectedDocs, setSelectedDocs] = useState<Set<string>>(new Set()) // 改为Set支持多选
  const [expandedDirectories, setExpandedDirectories] = useState<Set<string>>(new Set())
  const [loadingDirectories, setLoadingDirectories] = useState<Set<string>>(new Set())
  const [directoryData, setDirectoryData] = useState<DirectoryNode[]>(directories)

  // 当directories prop变化时更新本地数据
  useEffect(() => {
    setDirectoryData(directories)
  }, [directories])

  // 重置状态并设置智能默认值
  useEffect(() => {
    if (isOpen) {
      // 如果有当前选中的文档，默认选择"按文档导出"
      if (currentSelectedDocId) {
        setSelectedType(ExportType.SINGLE)
        setSelectedDocs(new Set([currentSelectedDocId]))
        // 自动展开包含该文档的目录
        expandParentDirectories(currentSelectedDocId)
      } else {
        setSelectedType(ExportType.PROJECT)
        setSelectedDocs(new Set())
      }
      setSelectedDirectory('')
    } else {
      // 关闭时重置所有状态
      setSelectedType(ExportType.PROJECT)
      setSelectedDirectory('')
      setSelectedDocs(new Set())
      setExpandedDirectories(new Set())
      setLoadingDirectories(new Set())
    }
  }, [isOpen, currentSelectedDocId])

  // 自动展开包含指定文档的父目录
  const expandParentDirectories = (docId: string) => {
    const findAndExpand = (nodes: DirectoryNode[], targetId: string): boolean => {
      for (const node of nodes) {
        if (node.id === targetId) {
          return true
        }
        if (node.children) {
          if (findAndExpand(node.children, targetId)) {
            setExpandedDirectories(prev => new Set([...prev, node.id]))
            return true
          }
        }
      }
      return false
    }
    findAndExpand(directoryData, docId)
  }

  // 动态加载子目录数据
  const loadChildDirectories = async (directoryId: string) => {
    if (!teamId || !projectId) {
      console.error('缺少teamId或projectId')
      return
    }

    try {
      setLoadingDirectories(prev => new Set([...prev, directoryId]))
      
      const res: ApiResponse = await api({
        url: '/doc/directory/getChildDirectoryAndDocList',
        method: 'post',
        data: {
          directoryId,
          projectId,
          teamId
        }
      })

      if (res && res.success) {
        const childDirectoryList = res.data?.childDirectoryList || []
        const childDocumentList = res.data?.childDocumentList || []

        // 转换目录数据
        const directories = childDirectoryList.map((dir: any) => ({
          id: dir.id,
          name: dir.name,
          type: 'folder' as const,
          hasChild: dir.hasChild,
          children: []
        }))

        // 转换文档数据
        const documents = childDocumentList.map((doc: any) => ({
          id: doc.docId,
          name: doc.docTitle,
          type: 'file' as const
        }))

        // 合并目录和文档，保持原有顺序
        const children = [...directories, ...documents].sort((a, b) => {
          // 目录排在前面
          if (a.type === 'folder' && b.type !== 'folder') return -1
          if (a.type !== 'folder' && b.type === 'folder') return 1
          return 0
        })

        // 更新目录数据，添加子节点
        setDirectoryData(prev => addChildrenToNode(prev, directoryId, children))
      } else {
        throw new Error(res.message || '获取子目录失败')
      }
    } catch (error: any) {
      console.error('获取子目录失败:', error)
    } finally {
      setLoadingDirectories(prev => {
        const newSet = new Set(prev)
        newSet.delete(directoryId)
        return newSet
      })
    }
  }

  // 辅助函数：为节点添加子节点
  const addChildrenToNode = (nodes: DirectoryNode[], parentId: string, children: DirectoryNode[]): DirectoryNode[] => {
    return nodes.map(node => {
      if (node.id === parentId) {
        return {
          ...node,
          children: [...children]
        }
      }
      if (node.children) {
        return {
          ...node,
          children: addChildrenToNode(node.children, parentId, children)
        }
      }
      return node
    })
  }

  // 切换目录展开状态
  const toggleDirectory = async (directoryId: string) => {
    const isCurrentlyExpanded = expandedDirectories.has(directoryId)
    
    if (isCurrentlyExpanded) {
      // 收起目录
      setExpandedDirectories(prev => {
        const newSet = new Set(prev)
        newSet.delete(directoryId)
        return newSet
      })
    } else {
      // 展开目录
      setExpandedDirectories(prev => new Set([...prev, directoryId]))
      
      // 查找目录节点
      const findNode = (nodes: DirectoryNode[], targetId: string): DirectoryNode | null => {
        for (const node of nodes) {
          if (node.id === targetId) return node
          if (node.children) {
            const found = findNode(node.children, targetId)
            if (found) return found
          }
        }
        return null
      }
      
      const node = findNode(directoryData, directoryId)
      
      // 如果目录有子节点但还没有加载过，则加载子目录数据
      if (node && node.hasChild && (!node.children || node.children.length === 0)) {
        await loadChildDirectories(directoryId)
      }
    }
  }

  // 处理导出类型变化
  const handleTypeChange = (type: ExportType) => {
    setSelectedType(type)
    // 切换类型时清空之前的选择
    setSelectedDirectory('')
    setSelectedDocs(new Set())
    
    // 如果是按文档导出且当前有选中的文档，自动选择
    if (type === ExportType.SINGLE && currentSelectedDocId) {
      setSelectedDocs(new Set([currentSelectedDocId]))
      expandParentDirectories(currentSelectedDocId)
    }
  }

  // 处理文档选择（多选）
  const handleDocSelection = (docId: string, checked: boolean) => {
    setSelectedDocs(prev => {
      const newSet = new Set(prev)
      if (checked) {
        newSet.add(docId)
      } else {
        newSet.delete(docId)
      }
      return newSet
    })
  }

  // 渲染目录树
  const renderDirectoryTree = (nodes: DirectoryNode[], depth = 0) => {
    return nodes.map(node => (
      <div key={node.id} style={{ marginLeft: `${depth * 20}px` }}>
          {node.type === 'folder' ? (
          <div className="group">
            <div className={cn(
              "flex items-center space-x-3 py-2 px-3 rounded-md transition-colors cursor-pointer",
              "hover:bg-gray-100 dark:hover:bg-gray-700",
              selectedType === ExportType.DIRECTORY && selectedDirectory === node.id && 
                "bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700"
            )}>
              <button
                onClick={() => toggleDirectory(node.id)}
                className="flex items-center justify-center w-5 h-5 rounded hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
                disabled={loadingDirectories.has(node.id)}
              >
                {loadingDirectories.has(node.id) ? (
                  <div className="w-4 h-4 border-2 border-gray-300 border-t-blue-500 rounded-full animate-spin" />
                ) : expandedDirectories.has(node.id) ? (
                  <ChevronDown className="w-4 h-4" />
                ) : (
                  <ChevronRight className="w-4 h-4" />
                )}
              </button>
              
              <FolderOpen className="w-5 h-5 text-blue-500" />
              <span className="flex-1 text-sm font-medium">{node.name}</span>
              
              {(selectedType === ExportType.DIRECTORY || selectedType === ExportType.CURRENT_DIRECTORY) && (
                <input
                  type="radio"
                  name="directory"
                  value={node.id}
                  checked={selectedDirectory === node.id}
                  onChange={(e) => setSelectedDirectory(e.target.value)}
                  className="ml-2"
                />
              )}
            </div>
            
            {expandedDirectories.has(node.id) && node.children && (
              <div className="mt-1">
                {renderDirectoryTree(node.children, depth + 1)}
              </div>
            )}
          </div>
        ) : (
          <div className={cn(
            "flex items-center space-x-3 py-2 px-3 rounded-md transition-colors cursor-pointer",
            "hover:bg-gray-100 dark:hover:bg-gray-700",
            selectedType === ExportType.SINGLE && selectedDocs.has(node.id) && 
              "bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-700"
          )}>
            <FileText className="w-5 h-5 text-green-500" />
            <span className="flex-1 text-sm">{node.name}</span>
            
              {selectedType === ExportType.SINGLE && (
              <Checkbox
                checked={selectedDocs.has(node.id)}
                onCheckedChange={(checked) => handleDocSelection(node.id, checked as boolean)}
                  className="ml-2"
                />
          )}
        </div>
        )}
      </div>
    ))
  }

  // 获取选中项目的名称和描述
  const getSelectedInfo = () => {
    const findNode = (nodes: DirectoryNode[], targetId: string): DirectoryNode | null => {
      for (const node of nodes) {
        if (node.id === targetId) {
          return node
        }
        if (node.children) {
          const found = findNode(node.children, targetId)
          if (found) return found
        }
      }
      return null
    }

    switch (selectedType) {
      case ExportType.PROJECT:
        return { name: projectName, description: '导出整个项目（包含所有目录和文档）' }
      case ExportType.SINGLE:
        if (selectedDocs.size > 0) {
          const docIds = Array.from(selectedDocs).join(',')
          const docNames = Array.from(selectedDocs).map(id => {
            const node = findNode(directoryData, id)
            return node?.name || '未命名文档'
          })
          return { 
            name: docNames.join(', '), 
            description: `导出 ${selectedDocs.size} 个文档` 
          }
        }
        break
      case ExportType.DIRECTORY:
        if (selectedDirectory) {
          const dir = findNode(directoryData, selectedDirectory)
          return { name: dir?.name || '', description: '导出目录及子目录（包含所有子目录和文档）' }
        }
        break
      case ExportType.CURRENT_DIRECTORY:
        if (selectedDirectory) {
          const dir = findNode(directoryData, selectedDirectory)
          return { name: dir?.name || '', description: '导出当前目录（不包含子目录）' }
        }
        break
    }
    return { name: '', description: '' }
  }

  // 处理导出
  const handleExport = () => {
    const { name } = getSelectedInfo()
    
    switch (selectedType) {
      case ExportType.PROJECT:
        onExport(ExportType.PROJECT)
        break
      case ExportType.DIRECTORY:
        if (selectedDirectory) {
          onExport(ExportType.DIRECTORY, undefined, selectedDirectory, name)
        }
        break
      case ExportType.CURRENT_DIRECTORY:
        if (selectedDirectory) {
          onExport(ExportType.CURRENT_DIRECTORY, undefined, selectedDirectory, name)
        }
        break
      case ExportType.SINGLE:
        if (selectedDocs.size > 0) {
          const docIds = Array.from(selectedDocs).join(',')
          onExport(ExportType.SINGLE, docIds, undefined, name)
        }
        break
    }
    
    onClose()
  }

  // 检查是否可以导出
  const canExport = () => {
    switch (selectedType) {
      case ExportType.PROJECT:
        return true
      case ExportType.DIRECTORY:
      case ExportType.CURRENT_DIRECTORY:
        return selectedDirectory !== ''
      case ExportType.SINGLE:
        return selectedDocs.size > 0
      default:
        return false
    }
  }

  const { name: selectedName, description: selectedDescription } = getSelectedInfo()

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-4xl max-w-[95vw]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Download className="w-5 h-5" />
            选择导出内容
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-8 px-2">
          {/* 导出类型选择 */}
          <div className="space-y-4">
            <Label className="text-sm font-medium">导出类型</Label>
            <RadioGroup value={selectedType} onValueChange={(value) => handleTypeChange(value as ExportType)}>
              <div className="space-y-4">
                <div className="flex items-center space-x-4 p-4 rounded-lg border hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
                  <RadioGroupItem value={ExportType.PROJECT} id="project" />
                  <Label htmlFor="project" className="flex items-center gap-3 cursor-pointer flex-1">
                    <Building2 className="w-5 h-5 text-blue-500" />
                    <div>
                      <div className="font-medium">导出整个项目</div>
                      <div className="text-sm text-gray-500">包含所有目录和文档</div>
                    </div>
                  </Label>
                  <span className="text-sm text-gray-500 bg-gray-100 dark:bg-gray-700 px-3 py-1 rounded">
                    {projectName}
                  </span>
                </div>
                
                <div className="flex items-center space-x-4 p-4 rounded-lg border hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
                  <RadioGroupItem value={ExportType.DIRECTORY} id="directory" />
                  <Label htmlFor="directory" className="flex items-center gap-3 cursor-pointer flex-1">
                    <FolderTree className="w-5 h-5 text-purple-500" />
                    <div>
                      <div className="font-medium">导出目录及子目录</div>
                      <div className="text-sm text-gray-500">包含所有子目录和文档</div>
                    </div>
                  </Label>
                </div>
                
                <div className="flex items-center space-x-4 p-4 rounded-lg border hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
                  <RadioGroupItem value={ExportType.CURRENT_DIRECTORY} id="currentDirectory" />
                  <Label htmlFor="currentDirectory" className="flex items-center gap-3 cursor-pointer flex-1">
                    <FolderOpen className="w-5 h-5 text-orange-500" />
                    <div>
                      <div className="font-medium">导出当前目录</div>
                      <div className="text-sm text-gray-500">仅当前目录，不包含子目录</div>
                    </div>
                  </Label>
                </div>
                
                <div className="flex items-center space-x-4 p-4 rounded-lg border hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
                  <RadioGroupItem value={ExportType.SINGLE} id="single" />
                  <Label htmlFor="single" className="flex items-center gap-3 cursor-pointer flex-1">
                    <FileText className="w-5 h-5 text-green-500" />
                    <div>
                      <div className="font-medium">按文档导出</div>
                      <div className="text-sm text-gray-500">选择多个文档进行导出</div>
                    </div>
                  </Label>
                </div>
              </div>
            </RadioGroup>
          </div>

          {/* 目录/文档选择 */}
          {(selectedType === ExportType.DIRECTORY || selectedType === ExportType.CURRENT_DIRECTORY || selectedType === ExportType.SINGLE) && (
            <div className="space-y-4">
              <Label className="text-sm font-medium">
                {selectedType === ExportType.SINGLE ? '选择文档' : '选择目录'}
              </Label>
              <div className="max-h-96 overflow-y-auto border rounded-lg p-4 bg-gray-50 dark:bg-gray-800">
                {renderDirectoryTree(directoryData)}
              </div>
            </div>
          )}

          {/* 选中项目信息 */}
          {selectedName && (
            <div className="p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-lg">
              <div className="text-sm font-medium text-blue-900 dark:text-blue-100">
                即将导出：{selectedName}
              </div>
              <div className="text-sm text-blue-700 dark:text-blue-300 mt-2">
                {selectedDescription}
              </div>
            </div>
          )}

          {/* 操作按钮 */}
          <div className="flex justify-end gap-3 pt-4">
            <Button variant="outline" onClick={onClose} className="px-6">
              取消
            </Button>
            <Button
              onClick={handleExport}
              disabled={!canExport()}
              className="flex items-center gap-2 px-6"
            >
              <Download className="w-4 h-4" />
              开始导出
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
} 